#include "robot.h"

Robot::Robot()
{

}
Robot::Robot(int id){
    this->ID=id;
    this->path=NULL;
    this->isWaiting=false;
    this->askForNext=true;
    this->grantedAccess=false;
    this->occupiedCell=NULL;
    this->onStage=false;
    this->path=new Path();
}

Robot::Robot(Robot* r){
    this->ID = r->ID;
    this->path = r->path;
    this->isWaiting = r->isWaiting;
    this->askForNext = r->askForNext;
    this->grantedAccess = r->grantedAccess;
    this->occupiedCell = r->occupiedCell;
    this->onStage = r->onStage;
    this->path = new Path();
}

Cell* Robot::getOccupiedCell()
{
    return occupiedCell;
}
void Robot::addCellToPath(Cell* cell){
    this->path->add(cell);
    cell->addToRobotPath(this);
}

void Robot::releaseCell(){
    Cell* cell = this->path->first();
    Cell* cellPreOccupied = this->occupiedCell;
    if (cellPreOccupied != NULL){
        cellPreOccupied->removeRobot(this);
        cellPreOccupied->removeGrant();
//        std::cout << "I've been already on stage\n";
//        std::cout<<"After releasing cell ";
        cellPreOccupied->printCell();
    }
    this->occupiedCell = cell;
    this->path->popFirst();

    //cell->removeRobot(this);
    //cell->removeGrant();

}


void Robot::setPath(Path *path){
    this->path=path;
    std::list<Cell*>::iterator it;
    for (it=path->begin();it!=path->end() ; ++it){
        (*it)->addToRobotPath(this);
    }
}

bool Robot::grantAccessToNextCell(){

    this->grantedAccess=true;
    path->first()->setGrantedRobot(this);
    //path->cells.pop_front();
    this->askForNext=false;
    return true;
}
int Robot::countPath(){
    return this->path->size();
}

void Robot::printRobot(){
    std::cout<<"robot "<<this->ID;
}
void Robot::printPath(){
    std::cout<<"r"<<this->getId()<<": ";
    this->path->printPath();
}

void Robot::move(){
    this->onMove=true;
    thread = new RobotThread();
    thread->setRobot(this);
    thread->start();
}
